#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
提示词工程工作流演示（支持人工反馈）
展示如何使用支持人工介入反馈的工作流来设计和优化AI提示词
"""

import asyncio
from typing import Dict, List, Any
from src.research_core import (
    create_prompt_engineering_workflow_with_feedback,
    create_simple_prompt_workflow_with_feedback,
    PromptEngineeringState,
    # PromptOptimizer,  # 新增的提示词优化模块
    # FeedbackCollector,  # 新增的人工反馈收集模块
    # PerformanceAnalyzer  # 新增的性能分析模块
)


async def demo_simple_prompt_workflow_with_feedback():
    """演示简单提示词工作流（支持反馈）"""
    print("=== 简单提示词工程工作流演示（支持人工反馈） ===\n")
    
    # 创建工作流
    workflow = create_simple_prompt_workflow_with_feedback()
    
    # 定义需求
    requirement = """
    我需要一个能够帮助用户写Python代码的AI助手提示词。这个助手应该能够：
    1. 理解用户的具体编程需求
    2. 提供清晰、可运行的代码示例
    3. 包含适当的注释解释代码逻辑
    4. 遵循Python最佳实践和PEP8规范
    5. 对于复杂问题，能够分步骤解答
    """
    
    # 初始化状态
    initial_state = PromptEngineeringState(
        requirement=requirement,
        requirement_analysis="",
        current_prompt=None,
        human_feedback=None,
        feedback_history=[],
        optimization_goal=None,
        prompt_evaluation=None,
        final_prompt=None,
        design_reasoning=None,
        iteration_count=0,
        workflow_complete=False,
        human_intervened=False,
        current_stage="start",
        quality_score=0.0,
        execution_time={},
        context_info={},
        metadata={},
        ab_test_results=None,
        performance_metrics=[],
        user_feedbacks=[],
        optimization_history=[],
        prompt_versions={},
        test_results=None,
        user_preferences={},
        domain_context=None,
        interaction_history=[],
        personalization_settings={},
        template_recommendations=[],
        quality_evaluation_details=None,
        ab_test_variants=[],
        quality_history=[],
        decision_log=[],
        workflow_metrics={}
    )
    
    # 执行工作流
    result = workflow.invoke(initial_state)
    
    print("需求分析:")
    print(result.get("requirement_analysis", "无分析结果"))
    print("\n" + "="*50 + "\n")
    
    print("最终生成的提示词:")
    print(result.get("final_prompt", "无提示词生成"))
    print("\n" + "="*50 + "\n")
    
    print("设计说明:")
    print(result.get("design_reasoning", "无设计说明"))

async def demo_advanced_prompt_workflow_with_feedback():
    """演示高级提示词工作流（支持反馈）"""
    print("=== 高级提示词工程工作流演示（支持人工反馈） ===\n")
    
    # 创建工作流
    workflow = create_prompt_engineering_workflow_with_feedback()
    
    # 定义需求
    requirement = """
    我需要一个能够帮助用户进行数据分析的AI助手提示词。这个助手应该能够：
    1. 理解用户的数据分析需求
    2. 根据需求推荐合适的分析方法
    3. 生成相应的Python代码（使用pandas, numpy等库）
    4. 解释分析结果的含义
    5. 提供数据可视化的建议
    6. 注意事项和局限性说明
    """
    
    # 初始化状态
    initial_state = PromptEngineeringState(
        requirement=requirement,
        requirement_analysis="",
        current_prompt=None,
        human_feedback=None,
        feedback_history=[],
        optimization_goal="提高提示词在数据分析任务中的指导性和完整性",
        prompt_evaluation=None,
        final_prompt=None,
        design_reasoning=None,
        iteration_count=0,
        workflow_complete=False,
        human_intervened=False,
        current_stage="start",
        quality_score=0.0,
        execution_time={},
        context_info={},
        metadata={},
        ab_test_results=None,
        performance_metrics=[],
        user_feedbacks=[],
        optimization_history=[],
        prompt_versions={},
        test_results=None,
        user_preferences={},
        domain_context=None,
        interaction_history=[],
        personalization_settings={},
        template_recommendations=[],
        quality_evaluation_details=None,
        ab_test_variants=[],
        quality_history=[],
        decision_log=[],
        workflow_metrics={}
    )
    
    # 执行工作流
    result = workflow.invoke(initial_state)
    
    print("需求分析:")
    print(result.get("requirement_analysis", "无分析结果"))
    print("\n" + "="*50 + "\n")
    
    print("最终生成的提示词:")
    print(result.get("final_prompt", "无提示词生成"))
    print("\n" + "="*50 + "\n")
    
    print("设计说明:")
    print(result.get("design_reasoning", "无设计说明"))
    
    print("\n反馈历史:")
    for feedback in result.get("feedback_history", []):
        print(f"- {feedback['type']}反馈 ({feedback['timestamp']}): {feedback['content']}")
    
    print("\n执行时间统计:")
    execution_time = result.get("execution_time", {})
    for stage, duration in execution_time.items():
        print(f"- {stage}: {duration:.2f}秒")
    
    print(f"\n最终质量评分: {result.get('quality_score', 0.0)}")

async def demo_prompt_workflow_with_human_feedback():
    """演示带有人工反馈的提示词工作流"""
    print("=== 带有人工反馈的提示词工程工作流演示 ===\n")
    
    # 创建工作流
    workflow = create_prompt_engineering_workflow_with_feedback()
    
    # 定义需求
    requirement = """
    我需要一个能够帮助用户进行机器学习模型选择的AI助手提示词。这个助手应该能够：
    1. 理解用户的具体机器学习任务（分类、回归、聚类等）
    2. 根据数据特征推荐合适的算法
    3. 提供模型训练和评估的指导
    4. 解释模型结果的含义
    5. 给出模型优化建议
    """
    
    # 初始化状态（包含人工反馈）
    initial_state = PromptEngineeringState(
        requirement=requirement,
        requirement_analysis="",
        current_prompt=None,
        human_feedback="请更加强调模型选择的可解释性和业务适用性，而不仅仅是准确性",
        feedback_history=[],
        optimization_goal="提高提示词在机器学习任务中的实用性",
        prompt_evaluation=None,
        final_prompt=None,
        design_reasoning=None,
        iteration_count=0,
        workflow_complete=False,
        human_intervened=True,  # 标记有人工介入
        current_stage="start",
        quality_score=0.0,
        execution_time={},
        context_info={},
        metadata={},
        ab_test_results=None,
        performance_metrics=[],
        user_feedbacks=[],
        optimization_history=[],
        prompt_versions={},
        test_results=None,
        user_preferences={},
        domain_context=None,
        interaction_history=[],
        personalization_settings={},
        template_recommendations=[],
        quality_evaluation_details=None,
        ab_test_variants=[],
        quality_history=[],
        decision_log=[],
        workflow_metrics={}
    )
    
    # 执行工作流
    result = workflow.invoke(initial_state)
    
    print("需求分析:")
    print(result.get("requirement_analysis", "无分析结果"))
    print("\n" + "="*50 + "\n")
    
    print("最终生成的提示词:")
    print(result.get("final_prompt", "无提示词生成"))
    print("\n" + "="*50 + "\n")
    
    print("设计说明:")
    print(result.get("design_reasoning", "无设计说明"))
    
    print("\n反馈历史:")
    for feedback in result.get("feedback_history", []):
        print(f"- {feedback['type']}反馈 ({feedback['timestamp']}): {feedback['content']}")
    
    print("\n执行时间统计:")
    execution_time = result.get("execution_time", {})
    for stage, duration in execution_time.items():
        print(f"- {stage}: {duration:.2f}秒")
    
    print(f"\n最终质量评分: {result.get('quality_score', 0.0)}")

async def main():
    """主函数"""
    await demo_simple_prompt_workflow_with_feedback()
    print("\n" + "="*70 + "\n")
    await demo_advanced_prompt_workflow_with_feedback()
    print("\n" + "="*70 + "\n")
    await demo_prompt_workflow_with_human_feedback()

if __name__ == "__main__":
    asyncio.run(main())